package com.taijihuabao.common.commonutils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 *
 * @author changhui.tu
 */
public final class Md5Utils {

    public static String encrypt(String strSrc) {
        try {
            //定义解密数组
            char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            //字符串转换字节数组
            byte[] bytes = strSrc.getBytes();
            //创建MD5核心对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //更新
            md.update(bytes);
            //(源码解释)通过执行填充等最终操作来完成哈希计算。在调用之后，digest将被重置。返回结果散列值的字节数组。
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("MD5加密出错！！+" + e);
        }
    }

    public static void main(String[] args) {
        System.out.println(Md5Utils.encrypt("123456"));
    }

}
